package handler

import (
	"day1106/cache"
	"day1106/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CommentList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	size, _ := strconv.Atoi(c.DefaultPostForm("size", "2"))
	offset := (page - 1) * size
	var data model.Comment
	redis_key := "comment_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
		model.DB.Limit(size).Offset(offset).Order("id desc").Find(&data)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
func CommentSearch(c *gin.Context) {
	fid, _ := strconv.Atoi(c.Query("fid"))
	var data model.Comment
	model.DB.Where("fid = ?", fid).Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
